package com.jun.util;

import com.jun.pojo.admin.SysAdmin;
import io.jsonwebtoken.*;

import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;

/**
 * Jwt工具类
 */
public class JwtUtil {
  public static final String COOKIE_KEY = "token";
  private static final String KEY = "jun123";

  public static String createJwt(SysAdmin sysAdmin) {
    Calendar expire = Calendar.getInstance();
    expire.add(Calendar.DATE, 1); //一天

    return Jwts.builder()
        .setId( String.valueOf(sysAdmin.getAdminId()) )
        .setSubject( sysAdmin.getAdminUsername() )
        .setIssuedAt(new Date(System.currentTimeMillis()))
        .setExpiration(expire.getTime())
        .signWith(SignatureAlgorithm.HS256, KEY)
        .compact();
  }

  public static String obtainSubject(String jwtStr) {
    Claims claims = parseJWT(jwtStr);
    return claims.getSubject();
  }

  private static Claims parseJWT(String jwtStr) {
    return Jwts.parser()
        .setSigningKey(KEY)
        .parseClaimsJws(jwtStr)
        .getBody();
  }

}
